﻿using System;
using System.IO;
using System.Text;
using System.Web.Hosting;
using System.Web.UI;
using System.Web.UI.WebControls;
using MPBlog.Core;

namespace MPBlog.UserControls
{
    /// <summary>
    /// 每个widget展现时的外包装
    /// </summary>
    public partial class WidgetContainerBase : UserControl
    {
        private bool processedLoad;

        /// <summary> 
        /// 要包装的widget 
        /// </summary> 
        protected WidgetBase Widget { get; set; }

        /// <summary> 
        /// 获得操作按钮的html代码
        /// </summary> 
        protected string AdminLinks
        {
            get
            {
                //根据用户是否登录，判断是否显示操作按钮（删除，修改等）
                //if (Security.IsAuthorizedTo(Rights.ManageWidgets)) 
                //{ 
                if (Widget != null)
                {
                    var sb = new StringBuilder();

                    Guid widgetId = Widget.WidgetId;

                    sb.AppendLine(string.Format("<a class=\"delete\" href=\"#\" onclick=\"MPBlog.ajax.widgetManage.remove(this,'{0}');return false\" title=\"{1} widget\"><span class=\"widgetImg imgDelete\">delete</span></a>",
                        widgetId, "delete"));
                    sb.AppendLine(string.Format("<a class=\"edit\" href=\"#\" onclick=\"MPBlog.ajax.widgetManage.remove('{0}', '{1}');return false\" title=\"{2} widget\"><span class=\"widgetImg imgEdit\">edit</span>",
                        Widget.Name, widgetId, "edit"));
                    sb.AppendLine(string.Format("<a class=\"move\" href=\"#\" onclick=\"MPBlog.ajax.widgetManage.remove('{0}');return false\" title=\"{1} widget\"><span class=\"widgetImg imgMove\">move</span></a>",
                        widgetId, "move"));

                    return sb.ToString();
                }
                //}

                return String.Empty;
            }
        }


        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            ProcessLoad();
        }


        internal void ProcessLoad()
        {
            if (processedLoad)
            {
                return;
            }


            Control widgetBody = FindControl("WidgetBody");

            if (widgetBody != null)
            {
                widgetBody.Controls.Add(Widget);
            }
            else
            {
                var warn = new LiteralControl
                               {
                                   Text = "无法在当前主题模板的部件容器中找到 ID 为 \"WidgetBody\" 的控件."
                               };
                Controls.Add(warn);
            }

            processedLoad = true;
        }


        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            // Hide the container if the Widget is null or also not visible. 
            Visible = (Widget != null) && Widget.Visible;
        }

        /// <summary> 
        /// 加载widgetContainer,用于包装widget，如果当前主题文件没有提供widgtContainer.ascx，则使用默认的容器 
        /// </summary> 
        public static WidgetContainerBase GetWidgetContainer(WidgetBase widgetBaseControl)
        {
            string widgetContainerFile = string.Format("~/themes/{0}/WidgetContainer.ascx", Blog.BlogTheme);
            bool fileExits = File.Exists(HostingEnvironment.MapPath(widgetContainerFile)); //主题文件夹中是否存在包装文件
            WidgetContainerBase widgetContainerBase = fileExits ? (WidgetContainerBase)widgetBaseControl.Page.LoadControl(widgetContainerFile): new DefaultWidgetContainer();
            widgetContainerBase.ID = "widgetContainer" + widgetBaseControl.ID;
            widgetContainerBase.Widget = widgetBaseControl;
            return widgetContainerBase;
        }
    }

    public sealed class DefaultWidgetContainer : WidgetContainerBase
    {
        /// <summary>
        /// 用来存放widget的容器
        /// </summary>
        private readonly PlaceHolder widgetBody = new PlaceHolder
                                                      {
                                                          ID = "WidgetBody"
                                                      };

        public DefaultWidgetContainer()
        {
            Controls.Add(widgetBody);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (Widget == null)
            {
                throw new NullReferenceException("无效的widget");
            }

            if (string.IsNullOrEmpty(Widget.Name))
            {
                throw new NullReferenceException("widget必须要有名字");
            }

            var sb = new StringBuilder();

            sb.AppendLine(" <div class=\"widget\">");
            sb.AppendLine(AdminLinks);
            if (Widget.ShowTitle)
            {
                sb.AppendLine(string.Format("   <h4>{0}</h4>", Widget.Title));
            }
            else
            {
                sb.AppendLine("<br />");
            }

            sb.AppendLine("    <div class=\"content\">");
            writer.Write(sb.ToString());
            base.Render(writer);
            writer.WriteLine("      </div>");
            writer.WriteLine("  </div>");
        }
    }
}